<template>
  <view class="region-picker-container">
    <!-- 遮罩层 -->
    <view 
      v-if="visible" 
      class="picker-mask" 
      @click="handleCancel"
    ></view>
    
    <!-- 选择器弹窗 -->
    <view 
      v-if="visible" 
      class="picker-popup"
      :class="{ 'picker-popup-show': visible }"
    >
      <!-- 头部 -->
      <view class="picker-header">
        <text class="picker-cancel" @click="handleCancel">取消</text>
        <text class="picker-title">选择地区</text>
        <text class="picker-confirm" @click="handleConfirm">确定</text>
      </view>
      
      <!-- 选择器内容 -->
      <picker-view 
        class="picker-view" 
        :value="pickerValue" 
        @change="handlePickerChange"
      >
        <!-- 省份列 -->
        <picker-view-column>
          <view 
            v-for="(province, index) in provinces" 
            :key="index" 
            class="picker-item"
          >
            {{ province }}
          </view>
        </picker-view-column>
        
        <!-- 城市列 -->
        <picker-view-column>
          <view 
            v-for="(city, index) in currentCities" 
            :key="index" 
            class="picker-item"
          >
            {{ city }}
          </view>
        </picker-view-column>
        
        <!-- 区县列 -->
        <picker-view-column>
          <view 
            v-for="(district, index) in currentDistricts" 
            :key="index" 
            class="picker-item"
          >
            {{ district }}
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>

<script>
import { formatRegionData, getDistrictsByProvinceAndCity } from '@/utils/regionData.js'

export default {
  name: 'RegionPicker',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      regionData: null,
      provinces: [],
      pickerValue: [0, 0, 0], // 当前选中的索引
      selectedRegion: {
        province: '',
        city: '',
        district: ''
      }
    }
  },
  computed: {
    // 当前省份对应的城市列表
    currentCities() {
      if (!this.regionData || this.pickerValue[0] >= this.regionData.cities.length) {
        return [];
      }
      return this.regionData.cities[this.pickerValue[0]] || [];
    },
    
    // 当前城市对应的区县列表
    currentDistricts() {
      if (!this.regionData || 
          this.pickerValue[0] >= this.regionData.districts.length ||
          this.pickerValue[1] >= this.regionData.districts[this.pickerValue[0]].length) {
        return [];
      }
      return this.regionData.districts[this.pickerValue[0]][this.pickerValue[1]] || [];
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initPicker();
      }
    },
    value: {
      handler(newVal) {
        if (newVal && newVal.length === 3) {
          this.initPickerValue(newVal);
        }
      },
      immediate: true
    }
  },
  created() {
    this.initRegionData();
  },
  methods: {
    // 初始化地区数据
    initRegionData() {
      this.regionData = formatRegionData();
      this.provinces = this.regionData.provinces;
    },
    
    // 初始化选择器
    initPicker() {
      if (this.value && this.value.length === 3) {
        this.initPickerValue(this.value);
      } else {
        this.pickerValue = [0, 0, 0];
        this.updateSelectedRegion();
      }
    },
    
    // 根据传入的值初始化选择器位置
    initPickerValue(regionArray) {
      const [province, city, district] = regionArray;
      
      // 查找省份索引
      const provinceIndex = this.provinces.findIndex(p => p === province);
      if (provinceIndex === -1) {
        this.pickerValue = [0, 0, 0];
        this.updateSelectedRegion();
        return;
      }
      
      // 查找城市索引
      const cities = this.regionData.cities[provinceIndex] || [];
      const cityIndex = cities.findIndex(c => c === city);
      if (cityIndex === -1) {
        this.pickerValue = [provinceIndex, 0, 0];
        this.updateSelectedRegion();
        return;
      }
      
      // 查找区县索引
      const districts = this.regionData.districts[provinceIndex][cityIndex] || [];
      const districtIndex = districts.findIndex(d => d === district);
      if (districtIndex === -1) {
        this.pickerValue = [provinceIndex, cityIndex, 0];
        this.updateSelectedRegion();
        return;
      }
      
      this.pickerValue = [provinceIndex, cityIndex, districtIndex];
      this.updateSelectedRegion();
    },
    
    // 处理选择器变化
    handlePickerChange(e) {
      const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
      
      // 如果省份改变，重置城市和区县
      if (provinceIndex !== this.pickerValue[0]) {
        this.pickerValue = [provinceIndex, 0, 0];
      }
      // 如果城市改变，重置区县
      else if (cityIndex !== this.pickerValue[1]) {
        this.pickerValue = [provinceIndex, cityIndex, 0];
      }
      // 否则直接更新
      else {
        this.pickerValue = [provinceIndex, cityIndex, districtIndex];
      }
      
      this.updateSelectedRegion();
    },
    
    // 更新选中的地区信息
    updateSelectedRegion() {
      const [provinceIndex, cityIndex, districtIndex] = this.pickerValue;
      
      this.selectedRegion = {
        province: this.provinces[provinceIndex] || '',
        city: this.currentCities[cityIndex] || '',
        district: this.currentDistricts[districtIndex] || ''
      };
    },
    
    // 确认选择
    handleConfirm() {
      const { province, city, district } = this.selectedRegion;
      
      if (!province || !city || !district) {
        uni.showToast({
          title: '请选择完整的省市区',
          icon: 'none'
        });
        return;
      }
      
      this.$emit('confirm', {
        province,
        city,
        district,
        value: [province, city, district]
      });
      
      this.handleCancel();
    },
    
    // 取消选择
    handleCancel() {
      this.$emit('cancel');
    }
  }
}
</script>

<style scoped>
.region-picker-container {
  position: relative;
}

.picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.picker-popup {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 1000;
  transform: translateY(100%);
  transition: transform 0.3s ease;
}

.picker-popup-show {
  transform: translateY(0);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  border-bottom: 2rpx solid #F0F0F0;
}

.picker-cancel {
  font-size: 32rpx;
  color: #999999;
}

.picker-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.picker-confirm {
  font-size: 32rpx;
  color: #D4AF37;
  font-weight: bold;
}

.picker-view {
  height: 500rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  font-size: 32rpx;
  color: #333333;
}
</style>
